package com.luoying.itew.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProviders;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonSharePoint;
import com.amap.api.services.share.ShareSearch;
import com.luoying.itew.R;
import com.luoying.itew.activity.InformationActivity;
import com.luoying.itew.activity.MainActivityViewModel;
import com.luoying.itew.adapter.MonitorAdapter;
import com.luoying.itew.bean.MonitorBean;
import com.luoying.itew.common.Constant;
import com.luoying.itew.databinding.FragmentListBinding;
import com.luoying.itew.util.MonitorUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;

/**
 * Created by lufan on 2019-04-23
 * Class describe
 */
public class ListDataFragment extends BaseFragment implements OnRefreshListener,
        MonitorAdapter.MonitorOnItemClickListener,ShareSearch.OnShareSearchListener,TextWatcher {
    /**
     * 列表适配器
     */
    private MonitorAdapter adapter;
    /**
     * ViewModel
     */
    private MainActivityViewModel mModel;
    /**
     * Binding
     */
    private FragmentListBinding binding;
    /**
     * 高德地图生成短传链接
     */
    private ShareSearch mShareSearch;

    /**
     * 微信开放平台
     */
    private IWXAPI iwxapi;
    /**
     * 分享监测点临时存放对象
     */
    private MonitorBean tempBean;

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_list;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        //生成ViewModel
        mModel = ViewModelProviders.of(getActivity()).get(MainActivityViewModel.class);
        //生成binding
        binding =  DataBindingUtil.inflate(inflater, R.layout.fragment_list,container,false);

        //创建适配器
        adapter = new MonitorAdapter(this,getContext());
        binding.setOnRefreshListener(this::onRefresh);
        binding.setAdapter(adapter);
        binding.setTextWatcher(this);

        mModel.getAllListMonitor().observe(this, monitorBeans -> {
            adapter.setList(monitorBeans);
            adapter.notifyDataSetChanged();
        });

        mModel.getRefresh().observe(this, aBoolean -> {
            if (aBoolean) {
                binding.monitorSmartrefreshLayout.autoRefresh();
            } else {
                binding.monitorSmartrefreshLayout.finishRefresh();
            }
        });
        binding.monitorSmartrefreshLayout.autoRefresh();
        regToWx();
        return binding.getRoot();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        adapter.getFilter().filter(charSequence);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    /**
     * 注册微信
     */
    public void regToWx(){
        iwxapi = WXAPIFactory.createWXAPI(getContext(), Constant.WEIXIN_OPEN_ID, true);
        iwxapi.registerApp(Constant.WEIXIN_OPEN_ID);
        mShareSearch = new ShareSearch(getContext().getApplicationContext());
        mShareSearch.setOnShareSearchListener(this);
    }

    @BindingAdapter({"onRefreshListener"})
    public static void loadImage(SmartRefreshLayout refreshLayout, OnRefreshListener listener) {
        if(refreshLayout!=null){
            refreshLayout.setOnRefreshListener(listener);
        }
    }

    /**
     * 点击微信分享回调
     * @param bean
     */
    @Override
    public void onItemShare(MonitorBean bean) {
        //高德地图 位置分享生成位置链接 异步
        LatLonSharePoint point = new LatLonSharePoint(bean.getBdLat(),
                bean.getBdLng(), "安泰监测点："+bean.getMonitorPointName());
        //临时存放对想
        tempBean = bean;
        mShareSearch.searchLocationShareUrlAsyn(point);
    }

    @Override
    public void onItemClick(MonitorBean monitorBean) {
        toDetailActivity(monitorBean);
    }

    public void toDetailActivity(MonitorBean monitorBean){
        Intent intent = new Intent(getContext(), InformationActivity.class);
        intent.putExtra("cuurMonitorId", monitorBean.getMonitorPointId());
        startActivity(intent);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mModel.getMapInfo();
    }

    @Override
    public void onPoiShareUrlSearched(String s, int i) {

    }

    @Override
    public void onNaviShareUrlSearched(String s, int i) {

    }

    /**
     * 位置分享的异步处理
     * @param s
     * @param i
     */
    @Override
    public void onLocationShareUrlSearched(String s, int i) {
        if(i == AMapException.CODE_AMAP_SUCCESS||tempBean==null){
            //生成成功 分享微信
            shareLocationToWx(s);
        } else{
            Toast.makeText(getContext(), "分享失败", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onBusRouteShareUrlSearched(String s, int i) {

    }

    @Override
    public void onWalkRouteShareUrlSearched(String s, int i) {

    }

    @Override
    public void onDrivingRouteShareUrlSearched(String s, int i) {

    }

    /**
         * 分享到微信
         * @param url 链接地址
         */
        public void shareLocationToWx(String url){
            //初始化一个WXWebpageObject，填写url
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = url;

            //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
            WXMediaMessage msg = new WXMediaMessage(webpage);
            //标题
            msg.title = getString(R.string.share_wx_title);

            String warn = "";

            switch (MonitorUtils.getMonitorState(tempBean)){
                default:
                case Constant.WARN_LEVEL_GREEN:
                    warn = getString(R.string.warn_leve_green);
                    break;
                case Constant.WARN_LEVEL_YELLOW:
                    warn = getString(R.string.warn_leve_yellow);
                    break;
                case Constant.WARN_LEVEL_ORANGE:
                    warn = getString(R.string.warn_leve_orange);
                    break;
                case Constant.WARN_LEVEL_RED:
                    warn = getString(R.string.warn_leve_red);
                    break;
            }
            //描述
            msg.description = String.format(getString(R.string.share_wx_description), tempBean.getMonitorArea().getDistrictName(),
                    tempBean.getMonitorPointName(), warn);
            Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.drawable.antai);
            msg.thumbData =bmpToByteArray(thumbBmp, true);

            //构造一个Req
            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = "webpage" + System.currentTimeMillis();
            req.message =msg;
            req.scene =SendMessageToWX.Req.WXSceneSession;

            //调用api接口，发送数据到微信
            iwxapi.sendReq(req);
        }

        public  byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
            if (needRecycle) {
                bmp.recycle();
            }

            byte[] result = output.toByteArray();
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return result;
    }
}
